<?php
/**
 * 《退货单》实现类
 *
 * @author 孙晓晔
 * @version $Id: Material.class.php 1020 2010-03-19 07:04:54Z sunxy $
 */
require_once(dirname(__FILE__) . '/MaterialUtil.class.php');

class Returned extends MaterialUtil {
	public $tbl = Constant::tbl_wl_returned;
	
	public $status = array(
		'-' => '请选择',
		'1' => '等待审核',
		'2' => '已经打印',
		'3' => '已经签字',
		// '4' => '取消信息',
		'8' => '取消信息',

		'9' => '其它',
	);

	public $orderby = array(
		'-' => '请选择',
		'date' => '入库日期',
		'emp' => '入库员',
		
		'supplier' => '供应商',
		'number' => '送货单',
		'purchase' => '订购单',
		// 'total' => '金额',
			
		'1' => '创建时间',
		'2' => '更新时间',
	);
	
	public $groupby = array(
		'-' => '请选择',
		'emp' => '入库员',
		'supplier' => '供应商',
		// 'currency' => '币种',

		'status' => '状态',
		'2' => '日期',
		'3' => '月份',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);
		
		$controller->assign('t1', strtotime('-3 month'));
		
		$emp = array(
			// '-' => '请选择',
			'emp' => '退货员',
			'oper' => '录入员',
		);
		
		$controller->assign_by_ref('emp_option', $emp);

		$controller->display($request, 'material/returned/find');
		return true;
	}

	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	function _where($request) {
		$purchase_s = $this->_input($request['purchase_s']);
		$receive_s = trim($request['receive_s']);
		
		$date1_s = $this->_input($request['date1_s']);
		$date2_s = $this->_input($request['date2_s']);
		
		$emp_t_s = $request['emp_t_s'];
		if ($emp_t_s == 'emp') {
			$request['emp_s'] = $request['emp_a_s'];
		} else if ($emp_t_s == 'oper') {
			$request['oper_s'] = $request['emp_a_s'];
		}

		$my = $this->_my();

		if (empty($my)) {
			$where = " WHERE 1=1";
		} else {
			$where = " WHERE " . $my;
		}

		if (!empty($purchase_s)) {
			$where .= " AND purchase = '" . $purchase_s . "'";
		}
		
		if (!empty($receive_s)) {
			$where .= " AND receive = '" . $receive_s . "%'";
		}
		
		if (!empty($date1_s)) {
			$where .= " AND date >= '" . $date1_s . "'";
		}
		
		if (!empty($date2_s)) {
			$where .= " AND date < '" . $date2_s . "'";
		}

		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}
	
	function _my() {
		if ($this->_is_admin()) {
			return '';
		}
	
		if ($this->_audit('60') || $this->_audit('68')) {
			return 'visible = 1 ';
		}
	
		$emp = $_SESSION['id'];
	
		return sprintf("visible = 1 (emp = '%s' OR oper = '%s')", $emp, $emp);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {

			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);
				
				$row['num_'] = $this->_num('returned', $row['id']);
				
				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}
		
		$controller->display($request, 'material/returned/list');
		
		return true;
	}
	
	function _is_cw() {
		if ($this->_is_admin()) {
			return true;
		}
		
		$dept = $_SESSION['dept'];
		if (preg_match("/^(cg|cw01)/i", $dept)) {
			return true;
		}
		
		return false;
	}
	
	function _num($field, $id) {
		require_once(dirname(__FILE__) . '/ReturnedItem.class.php');
		$aa = new ReturnedItem();
	
		return $aa->_count($field, $id);
	}
	
	function xls($controller, $request) {
		$this->pretreat($controller);
	
		$this->findPara($controller, $request);
	
		$request['tpl'] = "xls";
		
		require_once(dirname(__FILE__) . '/Purchase.class.php');
		$aa = new Purchase();
	
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);
	
		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			$row['purchase_x'] = $aa->_view($row['purchase']);
			
			$row['num_'] = $this->_num('returned', $row['id']);
				
			$row = $this->_orderby_x($controller, $row, $this->orderby_s);
	
			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);
	
		$filename = sprintf("%s.xls", date("YmdHis"));
		header('Content-Disposition:application/vnd.ms-excel; filename=' . $filename);
	
		$controller->display($request, 'material/returned/list');
		return true;
	}
	
	function bill($controller, $request) {
		$this->pretreat($controller);
	
		$this->findPara($controller, $request);
	
		$request['tpl'] = "xls";
		
		require_once(dirname(__FILE__) . '/Purchase.class.php');
		$aa = new Purchase();
		
		$insql = "in ('000000000";
		while (list($k, $v) = each($request)) {
			if (substr($k, 0, 2) == "c_") {
				$insql .= "', '" . $v;
			}
		}
		$insql .= "')";
	
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE id %s %s";
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $insql, $orderby);
		debug($sql);
	
		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			$row['purchase_x'] = $aa->_view($row['purchase']);
			
			$row['supplier_x'] = $row['purchase_x']['supplier_x'];
			
			$row['in_list'] = $this->_in_list($row['id']);
			
			debug(print_r($row, true));
	
			$row = $this->_orderby_x($controller, $row, $this->orderby_s);
	
			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);
	
		$filename = sprintf("%s.xls", date("YmdHis"));
		header('Content-Disposition:application/vnd.ms-excel; filename=' . $filename);
	
		$controller->display($request, 'material/returned/list_bill');
		return true;
	}
	
	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function add($controller, $request) {
		$this->pretreat($controller);
	
		$id = $request['id'];
		require_once 'Material.class.php';
		$material = new Material();
		$row = $material->_view($id);
	
		$controller->assign_by_ref('material', $row);
	
		$this->_my($controller, $row);
	
		$controller->display($request, 'material/returned/add');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'material/returned/edit');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);
		
		$date = $request['date'];

		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);

		$supplier = $this->_input($request['supplier']);
		$number = $request['number'];
		$purchase = $request['purchase'];
		
		$currency = $request['currency'];
		$total = $this->_total2('receive', $id);
		
		$content = $request['content'];

		$status = $request['status'];

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET office = '%s', emp = '%s', date = '%s', supplier = '%s', number = '%s', purchase = '%s'";
		$fmt .= ", total = '%s', content = '%s', status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $office, $emp, $date, $supplier, $number, $purchase, $total, $content, $status, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return true;
		}
			
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function _total2($field, $id) {
		require_once(dirname(__FILE__) . '/In.class.php');
		$aa = new In();
	
		return $aa->_total2($field, $id);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function view($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);
		
		require_once(dirname(__FILE__) . '/Purchase.class.php');
		$aa = new Purchase();
		
		$row['purchase_x'] = $aa->_view($row['purchase']);
		
		$row['supplier_x'] = $row['purchase_x']['supplier_x'];

		$controller->assign_by_ref('result', $row);
		
		$_list_returned_item = $this->_list_returned_item($id);
		$controller->assign_by_ref('list_returned_item', $_list_returned_item);

		$controller->display($request, 'material/returned/view');
		
		return true;
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}
	
		$row = $this->_view_t($row);
	
		return $row;
	}
	
	function _list_returned_item($id) {
		require_once(dirname(__FILE__) . '/ReturnedItem.class.php');
		$aa = new ReturnedItem();
	
		return $aa->_list($id);
	}
	
	function delete($controller, $request) {
		$this->pretreat($controller);
	
		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request)) {
			if (substr($k, 0, 2) <> "c_") {
				continue;
			}
			
			$row = $this->_view($id);
			if (!$this->_is_delete($row)) {
				continue;
			}
	
			$this->_delete3($id);
		}
	
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));
	
		$this->findPost($controller, $request);
		return true;
	}
	
	function _delete3($id) {
		$db = newdb($this->dsn_w);
		if ($this->_is_admin()) {
			$fmt = "DELETE FROM %s WHERE id = '%s'";
		} else {
			$fmt = "UPDATE %s SET visible = 2 WHERE id = '%s'";
		}
	
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$db->query($sql);
	}
	
	function _is_delete($row) {
		if ($this->_is_admin()) {
			return true;
		}
		
		if ($row['status'] < 2) {
			return true;
		}
	
		if ($this->_audit('153') || $this->_audit('154')) {
			return true;
		}
	
		$emp = $_SESSION['id'];
		
		if ($row['emp'] == $emp || $row['oper'] == $emp) {
			return true;
		}
	
		return false;
	}
	
	function batch_total($controller, $request) {
		$this->pretreat($controller);
	
		$insql = "in ('000000000";
		while (list($k, $v) = each($request)) {
			if (substr($k, 0, 2) == "c_") {
				$insql .= "', '" . $v;
			}
		}
		$insql .= "')";
	
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE id %s";
		$sql = sprintf($fmt, $this->tbl, $insql);
		debug($sql);
	
		$result = $db->query($sql);
		$data = array();
		$purchase = '';
		$supplier = '';
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
	
			$data[] = $row;
	
			// debug(print_r($row, true));
		}
		$controller->assign_by_ref('result', $data);
	
		$controller->display($request, 'material/returned/batch_total');
		return true;
	}
	
	function batch_totalPost($controller, $request) {
		$this->pretreat($controller);
	
		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request['cc'])) {
			$request['id'] = $id;
			
			$total = $this->_total2('receive', $id);
			
			$fmt = "UPDATE %s SET total = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $total, $id);
			debug($sql);
			$db->query($sql);
		}
	
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));
	
		$this->findPost($controller, $request);
		return true;
	}
	
	function day_update($controller, $request) {
		$this->pretreat($controller);
		
		
		$dd = date('Y-m-d', strtotime("-1 DAY"));
	
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE createtime > '%s'";
		$sql = sprintf($fmt, $this->tbl, $dd);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			// echo ".";
			
			$total = $this->_total2('receive', $row['id']);
			
			$fmt = "UPDATE %s SET total = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $total, $row['id']);
			$db->query($sql);
			if ($db->affected_rows() > 0) {
				// echo "U";
				echo $sql . "\nU\n";
			} else {
				echo ".";
			}
		}

		logdate($controller, $request);
		return true;
	}
	
	function split($controller, $request) {
		$this->pretreat($controller);
		
		$id = $request['id'];
		
		$row = $this->_view($id);
		
		$controller->assign_by_ref('result', $row);
	
		$_in_list = $this->_in_list($id);
		$controller->assign_by_ref('in_list', $_in_list);
	
		$controller->display($request, 'material/returned/split');
		return true;
	}
	
	function splitPost($controller, $request) {
		$this->pretreat($controller);
		
		$id = $request['id'];
		
		$number = $request['number'];
		
		require_once(dirname(__FILE__) . '/In.class.php');
		$aa = new In();
	
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			$receive = $this->_update($row['purchase'], $row['supplier'], $number, $row['date'], $row['emp']);
			
			while (list($k, $v) = each($request['cc'])) {
				$aa->_update_receive($v, $receive);
			}
		}
	
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));
	
		$this->findPost($controller, $request);
		return true;
	}

	function ajax_upload($controller, $request) {
		$s = print_r($request, true);
		debug($s);

		require_once 'HTTP/Upload.php';
		$upload = new HTTP_Upload('en');
		$file = $upload->getFiles('Filedata');
		if (PEAR::isError($file)) {
			die($file->getMessage());
		}

		if ($file->isValid()) {
			$now = date('Y-m-d H:i:s');

			$id = $request['id'];
			$name = $request['name'];
			if (empty($name) || $name == '-') {
				$name = 'uniq';
			}

			$dir = Download::dir($this->info_dir, $now, $id);
			debug($dir);
			if (!@file_exists($dir)) {
				umask();
				mkdir($dir, 0777, true);
			}

			$file->setName($name);
			$filename = $file->moveTo($dir);
			if (PEAR::isError($filename)){
				die($filename->getMessage());
			}

			$filesize = $file->upload['size'];

			$db = newdb($this->dsn);
			$fmt = "INSERT INTO %s(material, name, size, createtime)";
			$fmt .= " VALUES('%s', '%s', '%s', now())";
			$sql = sprintf($fmt, Constant::tbl_material_pic, $id, $filename, $filesize);
			debug($sql);
			$db->query($sql);
		}

		echo "1";
		return true;
	}
	
	function t($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);
		
		require_once(dirname(__FILE__) . '/In.class.php');
		$in = new In();
		
		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$aa = new RecordIn();

		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s ";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			
			$list = $aa->_list3($row['id']);
			while (list($k, $v) = each($list)) {
				$in->_update_receive22($v, $row['id'], $row['emp'], $row['date']);
			}
			
			// print_r($row);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function _update($purchase, $supplier, $receive, $date, $emp) {
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE receive = '%s' AND date = '%s'";
		$sql = sprintf($fmt, $this->tbl, $receive, $date);
		debug($sql);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			return $row['id']; 
		}
		
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		
		$fmt = "INSERT INTO %s(office, purchase, supplier, receive, date, emp, oper, createtime) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', now())";
		$sql = sprintf($fmt, $this->tbl, $office, $purchase, $supplier, $receive, $date, $emp, $_SESSION['id']);
		debug($sql);
		$db->query($sql);
		
		return $db->insert_id();
	}
	
	function group($controller, $request) {
		$this->pretreat_group($controller);
	
		$num = array(
			'1' => '按次数',
			'2' => '按金额',
		);
		$controller->assign('num_option', $num);
	
		$controller->assign('t1', strtotime('-1 month'));
		// $controller->assign('t2', strtotime('+1 day'));
	
		$controller->display($request, 'material/returned/group');
		return true;
	}
	
	function groupby($controller, $px) {
		$px = $this->groupby_aa($px, $this->groupby, 'emp');
	
		$controller->assign('groupby', $this->groupby[$px]);
	
		return $this->groupby_dd($px);
	}
	
	function groupby_dd($px) {
		if ($px == '1') {
			return "DATE_FORMAT(date, '%Y-%m-%d %H')";
		}
	
		if ($px == '2') {
			return "DATE_FORMAT(date, '%Y-%m-%d')";
		}
	
		if ($px == '3') {
			return "DATE_FORMAT(date, '%Y-%m')";
		}
	
		return $px;
	}
	
	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function groupPost($controller, $request) {
		$this->pretreat($controller);
			
		$this->groupPara($controller, $request);
	
		$num_s = $request['num_s'];
		if (!empty($num_s) && $num_s == '2') {
			$fmt = "SELECT %s AS a, SUM(total) AS c FROM %s a ";
		} else {
			$fmt = "SELECT %s AS a, COUNT(total) AS c FROM %s a ";
		}
		$sql = sprintf($fmt, $this->s, $this->tbl);
	
		$where = $this->_where($request);
	
		$request['sql'] = sprintf("%s %s GROUP BY %s ORDER BY %s %s", $sql, $where, $this->s, $this->orderby, $this->desc);
	
		$this->_group($controller, $request);
	
		// $controller->display($request, 'list');
		return true;
	}
	
	function _name($row, $px) {
		if (empty($px) || $px == '-' || $px == 'emp') {
			$row['a'] = sprintf("%s [%s]", Name::emp($row['a']), $row['a']);
		} elseif ($px == 'material') {
			$row['a'] = Name::material($row['a']);
		} else {
	
			$row = $this->_name_t($row, $px);
		}
	
		return $row;
	}
	
	function _has($field = 'receive', $id, $status = 'all') {
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT * FROM %s WHERE `%s` = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $field, $id);
		} else {
			$fmt = "SELECT * FROM %s WHERE `%s` = '%s' AND status = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $field, $id, $status);
		}
		debug($sql);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			return true;
		}
			
		return false;
	}
}
?>